﻿@{
    Layout = null;
    ViewData["Title"] = "Index";
}
<script src="~/js/vue.js"></script>
<script src="~/js/axios.js"></script>
<script src="~/element-ui/lib/index.js"></script>
<link rel="stylesheet" href="~/element-ui/lib/theme-chalk/index.css" />
<h1>RoleIndex角色管理</h1>
<div id="app">
    @*表单模块*@
    <div v-if="flagHid==1">
        <el-row :gutter="20">
            <el-col :span="6">
                当前角色总数：{{rows}}例
            </el-col>
        </el-row>
        <el-row :gutter="20">
            <el-col :span="3" :offset="21"><el-button type="success" round v-on:click="DialogVisibleAdd = true">添加角色</el-button></el-col>
        </el-row>
        <div style="margin:15px 0;"></div>
        @*用户查询的表单*@
        <el-table :data="roles"
                  border
                  style="width: 100%">
            <el-table-column fixed
                             label="序号"
                             type="index"
                             width="250">
            </el-table-column>
            <el-table-column fixed
                             prop="rid"
                             label="角色编号"
                             width="300">
            </el-table-column>
            <el-table-column fixed
                             prop="rname"
                             label="角色名称"
                             width="350">
            </el-table-column>
            <el-table-column fixed="right"
                             label="操作"
                             width="100">
                <template slot-scope="scope">
                    <el-button v-on:click="handleEdit(scope.row)" type="text">编辑</el-button>
                    <el-button type="text" v-on:click="handleDelete(scope.row.rid)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-on:size-change="handleSizeChange"
                       v-on:current-change="handleCurrentChange"
                       :current-page="pgcurrent"
                       :page-sizes="[3, 6, 9, 11]"
                       :page-size="pgsize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="rows">
        </el-pagination>
    </div>
    @*新增模块（模态框）*@
    <el-dialog title="提示"
               :visible.sync="DialogVisibleAdd"
               width="35%"
               center>
        <el-form :model="role" :rules="rules" ref="role" label-width="100px" class="demo-ruleForm">
            <el-form-item label="角色名称" prop="rname">
                <el-input v-model="role.rname"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button v-on:click="DialogVisibleAdd = false">取 消</el-button>
            <el-button type="primary" v-on:click="handleInsert('role')">确 定</el-button>
        </span>
    </el-dialog>
    @*修改模块*@
    <div v-if="flagHid==2">
        <el-row :gutter="20" style="margin-top:35px">
            <el-form ref="role" :model="role" :rules="rules" label-width="80px">
                <el-col :span="6">
                    <el-form-item label="角色编号">
                        <el-input v-model="role.rid" :disabled="true"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6" :offset="2">
                    <el-form-item label="角色名称" prop="rname">
                        <el-input v-model="role.rname"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="6" :offset="4">
                    <el-button type="success" round v-on:click="handleUpdate('role')">提交</el-button>
                    <el-button round style="margin-left:10px" v-on:click="flagHid=1">返回</el-button>
                </el-col>
            </el-form>
        </el-row>
        <div style="margin:15px 0;"></div>
        <div class="tree-container" style="height:700px;overflow:auto;">
            @*树形菜单*@
            <el-tree show-checkbox :data="menus" :props="defaultProps" ref="menutree"
                     node-key="mid" :default-expand-all="true" :default-checked-keys="meMenus">
            </el-tree>
        </div>
    </div>
</div>
<script type="text/javascript">
    var vue = new Vue({
        el: "#app",
        data: {
            pgsize: 3,
            pgcurrent: 1,
            rows: 0,
            //角色表单集合数据源
            roles: [],
            //角色类
            role: {
                rid: '',
                rname: '',
            },
            //隐藏标记
            flagHid: 1,
            //新增角色的模态框
            DialogVisibleAdd: false,
            //验证
            rules: {
                rname: [
                    { required: true, message: '请输入角色名称', trigger: 'blur' },
                ]
            },
            //树形菜单集合，用于分配权限
            menus: [],
            defaultProps: {
                children: 'children',
                label: 'mtext'
            },
            //已有的权限菜单
            meMenus: [],
            //树形菜单的ref
            menutree: [],
        },
        methods: {
            fillRoles() {
                axios.get("/Role/RoleFillRolesPG?pgsize=" + this.pgsize + "&pgcurrent=" + this.pgcurrent).then(res => {
                    this.roles = res.data.tabs;
                    this.rows = res.data.rows;
                });
            },
            //确认新增角色的的点击事件
            handleInsert(formRoles) {
                this.$refs[formRoles].validate(vali => {
                    if (vali) {
                        axios.post("/Role/RoleInsertRole", {
                            rname: this.role.rname,
                        }).then((res) => {
                            if (res.data > 0) {
                                this.openSuccess("成功添加角色！");
                                //清空表单，关闭模态框并刷新第一模块表格
                                //this.$refs[formRoles].resetFields();
                                this.role.rname = '';
                                this.DialogVisibleAdd = false;
                                this.fillRoles();
                            }
                        })
                    } else {
                        this.openError("请完成验证后再进行角色新增！");
                    }
                })
            },
            //编辑按钮点击事件
            handleEdit(row) {
                //置空
                //this.$refs.menus.setCheckedKeys([]);
                this.meMenus = [];
                this.flagHid = 2;
                this.role = row;
                //查询到所有的树形菜单栏
                axios.get("/Role/FillMenus").then(res => {
                    console.info("data:",res.data);
                    this.menus = res.data;
                });
                //根据角色ID查询到已有的权限,回显操作
                axios.get("/Role/FindMenusByRid?rid=" + row.rid).then(res => {
                    //这里的数据集为Int数组，是依据KeyID来进行的回显
                    this.meMenus = res.data;
                    console.info("回显的Menus：",this.meMenus);
                });
            },
            //确认修改按钮的点击事件
            handleUpdate(formRoles) {
                this.$refs[formRoles].validate(vali => {
                    if (vali) {
                        //创建角色和权限菜单的中间表对象集合
                        let checkedzhi = [
                            //全选中的菜单
                            ...this.$refs.menutree.getCheckedKeys(),
                            //半选中的菜单
                            ...this.$refs.menutree.getHalfCheckedKeys(),
                        ];
                        //接收的对象数组，稍后里面要拼成角色权限中间表对象
                        var jieshou = [];
                        //将全选和半选中的权限集进行拼接
                        checkedzhi.forEach((item) => {
                            jieshou.push({
                                rid: this.role.rid,
                                mid: item
                            });
                        });
                        //console.info("未拼接前：", checkedzhi);
                        //console.info("拼接后：", jieshou);
                        //此处提交两次请求，先修改角色表，然后对角色权限中间表进行权限的修改（先删后增）
                        axios.all([axios.post("/Role/RoleUpdateRole", this.role), axios.post("/Role/RoulMenuMidUdpOrAdd", jieshou)])
                            .then(axios.spread((res1, res2) => {
                                console.info(res1, res2);
                                this.openSuccess("成功修改了角色！");
                                //返回到第一部分并调用刷新
                                this.flagHid = 1;
                                this.fillRoles();
                            }))
                    } else {
                        this.openError("请完成验证后再进行角色修改！");
                    }
                })
            },
            //删除按钮点击事件
            handleDelete(rid) {
                this.$confirm("确定要删除该角色吗？", "温馨提示").then(res => {
                    axios.delete("/Role/RoleDeleteRole?rid=" + rid).then(res => {
                        if (res.data == 500) {
                            //说明这个角色下还有用户占用，无法被删除，进行提示
                            this.openError("该角色还有用户担任，请先删除其用户！");
                        } else {
                            this.openSuccess("成功删除角色！");
                            this.fillRoles();
                        }
                    })
                }).catch(err => {
                    this.openError("用户已取消删除操作");
                })
            },
            openSuccess(msg) {
                this.$notify({
                    title: '成功',
                    message: msg,
                    type: 'success'
                });
            },
            openError(msg) {
                this.$notify.error({
                    title: '错误',
                    message: msg
                });
            },
            handleSizeChange(val) {
                this.pgsize = val;
                this.fillRoles();
            },
            handleCurrentChange(val) {
                this.pgcurrent = val;
                this.fillRoles();
            }
        },
        mounted: function() {
            this.fillRoles();
        }
    })
</script>